﻿
using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Business;
using NetDon.OA.Data.CollectionClasses;
using NetDon.OA.Data.DaoClasses;
using NetDon.OA.Data.HelperClasses;
using NetDon.OA.Interface.Configuration;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NetDon.WebControls;
using NineRays.WebControls;
using SD.LLBLGen.Pro.ORMSupportClasses;
using NetDon.OA.Interface;


namespace NetDon.OA.Portal.Admin
{
    [Navigation("系统管理","日志维护")]
    public partial class EventManage : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txtStartDate_CalendarExtender.Format = SystemConfiguration.DateFormat;
                txtEndDate_CalendarExtender.Format = SystemConfiguration.DateFormat;
                //ddlApplication.InsertEmptyItem(ListEmptyType.All);

                LoadCategories();
                ShowLogs();
            }
        }

        private void LoadCategories()
        {
            var table = new DataTable();
            var fields = new EntityFields(1);
            fields[0] = LogFields.Category;
            var dao = new TypedListDAO();
            dao.GetMultiAsDataTable(fields, table, 0, new SortExpression(LogFields.Category | SortOperator.Ascending),
                                    null, null, false, null, null, 0, 0);
            foreach (DataRow row in table.Rows)
            {
                treeCategories.Nodes.Add(new FlyTreeNode(Convert.ToString(row[LogFields.Category.Name])));
            }
            if (treeCategories.Nodes.Count > 0)
            {
                treeCategories.SelectedNode = treeCategories.Nodes[0];
            }
        }

        protected void pagerLogs_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            var sort = new SortExpression(LogFields.LogTime | SortOperator.Descending);
            SortOperator sortOperator = SortOperator.Ascending;
            if (!string.IsNullOrEmpty(gridLogs.SortExpression) && gridLogs.SortDirection == SortDirection.Descending)
            {
                sortOperator = SortOperator.Descending;
            }
            switch (gridLogs.SortExpression)
            {
                case "LogTime":
                    sort = new SortExpression(LogFields.LogTime | sortOperator);
                    break;
                case "Type":
                    sort = new SortExpression(LogFields.Level | sortOperator);
                    break;
                case "Source":
                    sort = new SortExpression(LogFields.Source | sortOperator);
                    break;
                case "User":
                    sort = new SortExpression(LogFields.UserName | sortOperator);
                    break;
                case "Application":
                    sort = new SortExpression(LogFields.ApplicationName | sortOperator);
                    break;
            }
            var collection = new LogCollection();
            collection.GetMulti((PredicateExpression)e.Condition, 0, sort, null,
                                e.PageIndex + 1, e.PageSize);
            e.DataSource = collection;
        }

        protected void pagerLogs_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            var collection = new LogCollection();
            e.RecordCount = collection.GetDbCount((PredicateExpression)e.Condition);
        }

        protected void pagerLogs_PerformGetCondition(object sender, PerformGetConditionEventArgs e)
        {
            var predicate = new PredicateExpression(LogFields.Category == treeCategories.SelectedNode.Value);
            var format = new DateTimeFormatInfo
                             {
                                 ShortDatePattern = SystemConfiguration.DateFormat
                             };
            if (!string.IsNullOrEmpty(txtStartDate.Text.Trim()))
            {
                predicate &= LogFields.LogTime > DateTime.Parse(txtStartDate.Text, SystemConfiguration.DateTimeFormatInfo);
            }
            if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()))
            {
                predicate &= LogFields.LogTime < DateTime.Parse(txtEndDate.Text, SystemConfiguration.DateTimeFormatInfo).AddDays(1d);
            }
            //if (!string.IsNullOrEmpty(ddlApplication.SelectedValue))
            //{
            //    predicate &= LogFields.ApplicationName == ddlApplication.SelectedValue;
            //}
            if (!string.IsNullOrEmpty(ddlLogLevel.SelectedValue))
            {
                predicate &= LogFields.Level == (int)ddlLogLevel.SelectedValue.ToEnum<LogLevel>();
            }
            if (!string.IsNullOrEmpty(txtUser.Text.Trim()))
            {
                predicate &= LogFields.UserName % ("%" + txtUser.Text.Trim() + "%");
            }
            e.Condition = predicate;
        }

        protected void gridLogs_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var btnView = e.Row.FindControl("btnView") as ImageButton;
                if (btnView != null)
                {
                    btnView.OnClientClick = string.Format("showEventView('{0}');return false;",
                                                          DataBinder.Eval(e.Row.DataItem, "LogId"));
                }
            }
        }

        protected void gridLogs_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DeleteEvent")
            {
                var collection = new LogCollection();
                collection.DeleteMulti(LogFields.LogId == e.CommandArgument.ToString().ToGuid());
                pagerLogs.ReloadCurrentPage();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            DateTime dateBegin = new DateTime();
            DateTime dateEnd = new DateTime();

            if (txtStartDate.Text.Trim().Length > 0 && !DateTime.TryParseExact(txtStartDate.Text.Trim(), SystemConfiguration.DateFormat, SystemConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateBegin))
            {
                base.Alert("请输入正确的开始日期。");
                return;
            }

            if (txtEndDate.Text.Trim().Length > 0 && !DateTime.TryParseExact(txtEndDate.Text.Trim(), SystemConfiguration.DateFormat, SystemConfiguration.DateTimeFormatInfo, DateTimeStyles.AllowWhiteSpaces, out dateEnd))
            {
                base.Alert("请输入正确的结束日期。");
                //base.Alert(GetResourceString("EventEndDate"));
                return;
            }
            pagerLogs.PerformQuery();
        }

        private void ShowLogs()
        {
            if (treeCategories.SelectedNode != null)
            {
                btnSearch.Enabled = true;
                foreach (FlyTreeNode node in treeCategories.Nodes)
                {
                    node.ImageUrl = node.Selected ? ApplicationImages.TreeNodeOpened : ApplicationImages.TreeNodeClosed;
                }
                pagerLogs.PerformQuery();
            }
            else
            {
                btnSearch.Enabled = false;
            }
        }

        protected void btnChangeCategory_Click(object sender, EventArgs e)
        {
            txtUser.Text = string.Empty;
            txtStartDate.Text = string.Empty;
            txtEndDate.Text = string.Empty;
            ddlLogLevel.SelectedValue = string.Empty;
            //ddlApplication.SelectedValue = string.Empty;
            ShowLogs();
        }
    }
}